package com.as.downloadas.down;

import android.annotation.SuppressLint;
import android.app.DownloadManager;
import android.app.DownloadManager.Request;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;


/**
 * 下载
 */
public class DownloadManger {

    private String TAG = DownloadManger.class.getSimpleName();
    private static final String DIR_APK = "apk";
    private long downLoadTag;

    private final DownloadManager downloadManager;
    private final DownloadChangeObserver downloadObserver;
    private final Context ctx;

    public static DownloadManger instance;

    private DownloadListener listener;

    private Request request = null;
    private List<String> downUrlList;
    private boolean isMoreLineDown = false;
    private boolean isRegisterReceiver = false;
//    private List<AppPackgeList> mPackageList;


    private static final Uri CONTENT_URI = Uri.parse("content://downloads/my_downloads");

    private Map<String, String> urlMap = new HashMap<>();

    int apkDownIndex = 0;

    private DownloadManger(Context context) {
        ctx = context;
        downloadManager = (DownloadManager) ctx.getSystemService(Context.DOWNLOAD_SERVICE);
        downloadObserver = new DownloadChangeObserver(new Handler(Looper.getMainLooper()));
    }

    public static DownloadManger getInstance(Context context) {
        if (null == instance) {
            instance = new DownloadManger(context);
        }

        return instance;
    }

    public void registerReceiver() {
        if (isRegisterReceiver) {
            return;
        }
        ctx.registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
        ctx.getContentResolver().registerContentObserver(CONTENT_URI, true, downloadObserver);
        isRegisterReceiver = true;
    }

    public void unregisterReceiver() {
        if (!isRegisterReceiver) {
            return;
        }
        ctx.unregisterReceiver(receiver);
        ctx.getContentResolver().unregisterContentObserver(downloadObserver);
        isRegisterReceiver = false;
    }

    public String getUUID(String url) {
        return UUID.randomUUID().toString() + ".apk";
    }

    public void start(DownloadListener listener, String downUrl) {
        String fileName = getUUID(downUrl);
        registerReceiver();
        this.listener = listener;
        request = new Request(Uri.parse(downUrl));
        //
//        request = new Request(Uri.parse("https://www.baidu.com"));
        request.setTitle("下载");
        request.setDescription("正在下载中...");
        Log.e(TAG,"文件名称：" + fileName);
        Log.e(TAG,"文件是否存在====》" + isFolderExist(fileName));

        urlMap.put(downUrl, fileName);
        request.setDestinationInExternalFilesDir(ctx, DIR_APK, fileName);
        downLoadTag = downloadManager.enqueue(request);
        File dir = ctx.getExternalFilesDir(DIR_APK);
        String file = Uri.withAppendedPath(Uri.fromFile(dir), fileName).toString();
        listener.onFileCreated(downUrl, file);
    }

    public void start(DownloadListener listener, List<String> downUrl, int index) {
        registerReceiver();
        isMoreLineDown = true;
        this.apkDownIndex = index;
        this.downUrlList = downUrl;
        this.listener = listener;
        String uri = downUrlList.get(apkDownIndex);
        String fileName = getUUID(uri);
        Log.e(TAG,"当前下载的url=====》" + uri);

        request = new Request(Uri.parse(uri));
        request.setTitle("下载");
        request.setDescription("正在下载中...");
        Log.e(TAG,"文件名称=====》" + fileName);


        if (isFolderExist(fileName)) {
            request.setDestinationInExternalFilesDir(ctx, DIR_APK, fileName);
            File dir = ctx.getExternalFilesDir(DIR_APK);
            String file = Uri.withAppendedPath(Uri.fromFile(dir), fileName).toString();
            listener.onFileCreated(uri, file);
            downLoadTag = downloadManager.enqueue(request);
            Log.e(TAG,"开始下载=====》" + uri);

        }
    }


    private boolean isFolderExist(String dir) {
        File folder = Environment.getExternalStoragePublicDirectory(dir);
        return (folder.exists() && folder.isDirectory()) || folder.mkdirs();
    }

    public void cancel(long tag) {
        downloadManager.remove(tag);
    }

    class DownloadChangeObserver extends ContentObserver {

        public DownloadChangeObserver(Handler handler) {
            super(handler);
        }

        @Override
        public void onChange(boolean selfChange) {
            super.onChange(selfChange);
            queryDownloadStatus();
        }
    }

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.e(TAG,"下载完成=====》" );

            try {
                if (!isMoreLineDown) {
                    unregisterReceiver();
//                } else if (isMoreLineDown && apkDownIndex == downUrlList.size() - 1)//最后一条的时候我才关闭监听广播
                } else if (isMoreLineDown && apkDownIndex >= downUrlList.size())//标记大于列表才关闭广播
                {
                    unregisterReceiver();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

//    private void install(Context context) {
//        CommonUtils.installApk(context, ctx.getExternalFilesDir(null).getPath() + "/" + ctx.getPackageName() + "/"
//                + ctx.getPackageName() + CommonUtils.getVersionCode(ctx, ctx.getPackageName()) + ".apk");
//    }

    /**
     * 检查下载状态
     */
    @SuppressLint("Range")
    private void queryDownloadStatus() {
        DownloadManager.Query query = new DownloadManager.Query();
        query.setFilterById(downLoadTag);
        Cursor c = downloadManager.query(query);
        if (c != null && c.moveToFirst()) {
             int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
            Log.e(TAG,"下载状态.STATUS=====》 " +status);

            long currSizeIdx = c.getLong(c.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
            long fileTotalSize = c.getLong(c.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
            String uri = c.getString(c.getColumnIndex(DownloadManager.COLUMN_URI));
            int col = c.getColumnIndex("hint");
            String file = urlMap.get(uri);
            if (col > 0) {
                file = c.getString(col);
            }
            switch (status) {
                case DownloadManager.STATUS_PAUSED://下载暂停
                    Log.e(TAG,"下载暂停");

//                    LiveEventBus.get("modifyStatus").post("下载暂停");

                    break;
                case DownloadManager.STATUS_PENDING://下载延迟
                    Log.e(TAG,"下载延迟");
                    break;
                case DownloadManager.STATUS_RUNNING://正在下载
                    Log.e(TAG,"正在下载");
                    //正在下载，不做任何事情
                    if (currSizeIdx != 0) {
                        listener.refreshProgress((int) Math.round((currSizeIdx / (double) fileTotalSize) * 100));
                    }
                    break;
                case DownloadManager.STATUS_SUCCESSFUL://下载完成
                    Log.e(TAG,"下载完成");

                    listener.downloadSucc(uri, file);
                    removeUri(uri);
                    //完成
                    apkDownIndex++;
//                    LiveEventBus.get("modifyStatus").post("");

                    break;
                case DownloadManager.STATUS_FAILED://下载失败
                    Log.e(TAG,"下载失败");

                    removeUri(uri);
                    downloadManager.remove(downLoadTag);
                    if (isMoreLineDown) {
                        apkDownIndex++;
                        if (apkDownIndex <= downUrlList.size() - 1) {
                            start(this.listener, this.downUrlList, this.apkDownIndex);
                        }else{
//                            LiveEventBus.get("modifyStatus").post("下载失败，请重试");
                        }
                    }

                    //清除已下载的内容，重新下载
                    break;
            }
            c.close();
        }
    }

    /**
     * 在主线程调用, 不担心锁的问题
     * @param uri
     */
    private void removeUri(String uri) {
        if (!urlMap.containsKey(uri)) {
            return;
        }
        urlMap.remove(uri);
    }

}
